from flask import request
from src.api.origin import *
from src.schema import Schema
from src.core.user import User_Info
from src.core.user import User_Manager
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt, decode_token


@capture_exception
@request_record(result_print=False)
def login():
    """用户登录"""
    schema = Schema.login(**request.get_json(force=True))
    return User_Manager.login(schema)


@basic_decorator()
def logout(user):
    """用户登出"""
    jti = get_jwt()["jti"]
    blacklist.add(jti)
    return SUCCESS_CODE.LOGOUT_SUCCESS()


@basic_decorator()
def signup(user):
    """用户注册"""
    schema = Schema.signup(**request.get_json(force=True))
    return User_Manager.signup(schema)


@basic_decorator()
def remove_user(user):
    """删除用户"""
    schema = Schema.remove_user(**request.get_json(force=True))
    return User_Manager.remove_user(schema)


@basic_decorator()
def update_user(user):
    """更新用户信息"""
    schema = Schema.update_user(**request.get_json(force=True))
    return User_Manager.update_user(schema)


@basic_decorator()
def user_list(user):
    """获取用户列表"""
    schema = Schema.user_list(**request.get_json())
    return User_Info.user_list(schema)


@basic_decorator(result=False, multi_nodes=False)
def user_info(user):
    """获取用户信息"""
    schema = Schema.user_info(**request.get_json())
    return User_Info.user_info(schema)


# @request_record(False)
@jwt_required(refresh=True)
def refresh_token():
    """
    刷新 Access Token 的接口
    请求需携带有效的刷新token
    成功返回新的access token
    """
    # 获取当前用户身份
    current_user = get_jwt_identity()
    jwt_data = get_jwt()  # 获取当前token的相关信息
    return User_Manager.refresh_token(current_user, jwt_data)


@basic_decorator()
def change_passwd(user):
    """修改密码"""
    schema = Schema.update_passwd(**request.get_json())
    return User_Manager.update_passwd(schema)


@jwt_required(refresh=True)
def check_token():
    """验证刷新令牌是否有效（包括黑名单检查）"""
    json_data = request.get_json(force=True)
    refresh_token = json_data.get("refresh_token", None)
    if not refresh_token:
        return ERROR_CODE.TOKEN_INVALID()
    current_jwt = get_jwt()
    if current_jwt["jti"] != decode_token(refresh_token)["jti"]:
        return ERROR_CODE.TOKEN_MISMATCH()
    if refresh_token in blacklist:
        return ERROR_CODE.TOKEN_REVOKED()
    return SUCCESS_CODE.TOKEN_ACTIVE()
